import os

from dotenv import load_dotenv

from repair.material import extract_materials_info
from repair.tracks import get_tracks_info
from pprint import pprint

load_dotenv()
base_path = os.path.join(
    # LOCALAPPDATA 是 Windows 系统中的一个环境变量，表示当前用户的本地应用程序数据存储路径
    # C:\Users\<用户名>\AppData\Local
    os.getenv("LOCALAPPDATA"),
    "JianyingPro\\User Data\\Projects\\com.lveditor.draft"
)

import json
from jsonpath_ng import parse

def update_tracks_field_by_material_name(data, target_material_name, field_name, new_value):
    """
    根据 material_name 自动构建 JSONPath 表达式，并批量更新 tracks.segments 中的指定字段。

    :param data: JSON 数据
    :param target_material_name: 要匹配的素材名称
    :param field_name: 要修改的字段名，如 "render_index"
    :param new_value: 新值
    :return: 修改后的 data
    """

    # Step 1: 构建 material_name -> material_id 映射
    materials = data.get('materials', {}).get('videos', [])
    name_to_ids = {}
    for item in materials:
        mid = item.get('id')
        path = item.get('path')
        if path:
            filename = path.split('/')[-1].split('.')[0]
            if filename and mid:
                name_to_ids.setdefault(filename, []).append(mid)

    print(f"🔍 名称 → ID 映射：{name_to_ids}")
    target_ids = name_to_ids.get(target_material_name, [])
    print(f"🎯 匹配素材 ID 列表：{target_ids}")

    if not target_ids:
        print(f"⚠️ 未找到 material_name == '{target_material_name}' 的素材 ID")
        return data

    # Step 2: 遍历所有 target_id，构造 JSONPath 并更新字段
    for mid in target_ids:
        expr_str = f"$.tracks[*].segments[?material_id == '{mid}']"
        expr = parse(expr_str)
        print(expr)
        expr_str = f"$.tracks[*].segments[?material_id == '{mid}'].{field_name}"
        expr = parse(expr_str)

        matches = expr.find(data)
        if not matches:
            print(f"⚠️ 未找到 material_id == '{mid}' 的匹配项")
            continue

        print(f"✅ 正在更新 {mid} 的 `{field_name}` 字段为 {new_value}")
        for match in matches:
            match.context.update(match.path, new_value)

    return data


if __name__ == "__main__":
    # 使用示例
    json_file_path = base_path + r'\模版9_图片口播\draft_content.json'  # 替换为你的 JSON 文件路径
    with open(json_file_path, 'r', encoding='utf-8') as file:  # 明确指定编码为 utf-8
        data = json.load(file)
    # materials = extract_video_info(data)
    # # pprint(materials)
    # tracks = get_tracks_info(materials, data)
    # pprint(tracks)

    # 2. 使用 JSONPath 修改 tracks.segments.render_index 字段
    updated_data = update_tracks_field_by_material_name(
        data=data,
        target_material_name="图片_1",
        field_name="render_index",
        new_value=999
    )
    with open(json_file_path, 'r', encoding='utf-8') as file:  # 明确指定编码为 utf-8
        data = json.load(file)
    materials = extract_materials_info(data)
    # pprint(materials)
    tracks = get_tracks_info(materials, data)
    pprint(tracks)
    # 4. 写回 JSON 文件
    with open(json_file_path, 'w', encoding='utf-8') as f:
        json.dump(updated_data, f, ensure_ascii=False, indent=2)

    print("✅ JSON 文件更新完成")
